package com.sky.loveshop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.loveshop.entity.OrderDetail;
import com.sky.loveshop.entity.OrderInfo;
import com.sky.loveshop.entity.Shop;
import com.sky.loveshop.entity.aliPay.NotifyMessage;
import com.sky.loveshop.entity.qo.OrderInfoQO;
import com.sky.loveshop.entity.vo.OrderInfoVO;
import com.sky.loveshop.mapper.OrderInfoMapper;
import com.sky.loveshop.service.OrderDetailService;
import com.sky.loveshop.service.OrderInfoService;
import com.sky.loveshop.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/9/1 2:15
 */
@Slf4j
@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShopService shopService;


    @Override
    public List<OrderInfoVO> listOrderInfo(OrderInfoQO orderInfoQO) {
        return orderInfoMapper.searchAll(orderInfoQO);
    }

    @Override
    public PageInfo<OrderInfoVO> listOrderInfoPages(OrderInfoQO orderInfoQO) {
        PageHelper.startPage(orderInfoQO.getPageNum(), orderInfoQO.getPageSize());
        List<OrderInfoVO> orderInfoVOS = orderInfoMapper.searchAll(orderInfoQO);
        List<Integer> shopIds = orderInfoVOS.stream().map(OrderInfo::getShopId).distinct().collect(Collectors.toList());
        Map<Integer, String> id2ShopNameMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(shopIds)) {
            List<Shop> shopsByIds = shopService.getShopsByIds(shopIds);
            id2ShopNameMap = shopsByIds.stream().collect(Collectors.toMap(Shop::getId, Shop::getName));
        }
        Map<Integer, String> finalId2ShopNameMap = id2ShopNameMap;
        orderInfoVOS.stream().forEach(s -> {
            s.setShopName(finalId2ShopNameMap.get(s.getShopId()));
        });
        return new PageInfo<>(orderInfoVOS);
    }

    @Override
    public OrderInfoVO getOrderInfoById(Integer id) {
        OrderInfoVO vo = new OrderInfoVO();
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(orderInfo, vo);
        List<OrderDetail> orderDetailList = orderDetailService.getDetailListByOrderId(id);
        vo.setOrderDetailList(orderDetailList);
        return vo;
    }

    @Override
    public Integer addOrderInfo(OrderInfo orderInfo) {
        orderInfo.setCreateTime(new Date());
        return orderInfoMapper.insert(orderInfo);
    }

    @Override
    public Integer delOrderInfoById(Integer id) {
        return orderInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer updateOrderInfoById(OrderInfo orderInfo) {
        // 必选先将之前的所有字段先查出来，在重新赋值进去更新，不然会将其他字段更新没
        OrderInfo old = orderInfoMapper.selectByPrimaryKey(orderInfo.getId());
        old.setOrderNo(orderInfo.getOrderNo());
        return orderInfoMapper.updateByPrimaryKey(old);
    }

    @Override
    public List<OrderInfo> getOrderInfoListByIds(List<Integer> ids) {
        return orderInfoMapper.getOrderInfoListByIds(ids);
    }

    @Override
    public void updateOrderInfoByOutTradeNo(NotifyMessage msg) {

        Example example1 = new Example(OrderInfo.class);
        example1.createCriteria().andEqualTo("orderNo", msg.getOut_trade_no());
        OrderInfo orderInfo = orderInfoMapper.selectOneByExample(example1);
        orderInfo.setTradeNo(msg.getTrade_no());
        orderInfo.setOrderStatus(1);
        orderInfo.setUpdateTime(new Date());

        Example example = new Example(OrderInfo.class);
        example.createCriteria().andEqualTo("orderNo", msg.getOut_trade_no());
        int updatedRows = orderInfoMapper.updateByExample(orderInfo, example);
        if (updatedRows > 0) {
            log.info("orderPayNotifyCallBack 订单状态更新成功【异步回调监听订单状态】 {}", JSONUtil.toJsonStr(orderInfo));
        } else {
            log.info("orderPayNotifyCallBack 订单状态更新失败【异步回调监听订单状态】 {}", JSONUtil.toJsonStr(orderInfo));
        }
    }

    @Override
    public void updateOrderStatus(OrderInfo orderInfo) {
        Example example = new Example(OrderInfo.class);
        example.createCriteria().andEqualTo("orderNo", orderInfo.getOrderNo());
        int updatedRows = orderInfoMapper.updateByExample(orderInfo, example);
        if (updatedRows > 0) {
            log.info("updateOrderStatus 订单状态更新成功 {}", JSONUtil.toJsonStr(orderInfo));
        } else {
            log.info("updateOrderStatus 订单状态更新失败 {}", JSONUtil.toJsonStr(orderInfo));
        }
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        Example example1 = new Example(OrderInfo.class);
        example1.createCriteria().andEqualTo("orderNo", orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOneByExample(example1);
        return orderInfo;
    }

    @Override
    public void updateOrderQueryTimes(String orderNo) {
        orderInfoMapper.updateOrderQueryTimes(orderNo);
    }

    @Override
    public List<OrderInfo> getUnPayOrderList() {
        return orderInfoMapper.getUnPayOrderList();
    }
}
